﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using DapperWrapper;
using Newtonsoft.Json;
using ZL.Web.Utility;
using ZL.Web.Utility.Cache;
using ZL.Web.Utility.Config;
using ZL.Web.Utility.Mongodb;
using ZLWeb.WebApiEntityBase;

namespace ZLWeb.WebApiInfrastructure.Filter
{
    [AttributeUsage(AttributeTargets.Class)]
    public class AuthorizationValidateAtrribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.All(tr => tr.Key != "accesstoken"))
            {
                ResponseResultInfo error = new ResponseResultInfo();
                error.Description = "缺少Token拒绝访问";
                actionContext.Response =
                actionContext.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, error);
                return;
            }
            if (actionContext.Request.Headers.All(tr => tr.Key != "requestguid"))
            {
                ResponseResultInfo error = new ResponseResultInfo();
                error.Description = "缺少RequestGuid拒绝访问!";
                actionContext.Response =
                actionContext.Request.CreateResponse(HttpStatusCode.NonAuthoritativeInformation, error);
                return;
            }
            string AccessToken = actionContext.Request.Headers.GetValues("accesstoken").FirstOrDefault();
            string RequestGuid = actionContext.Request.Headers.GetValues("requestguid").FirstOrDefault();
            string key = string.Format("{0}@{1}", 
                   ZLConfig.TokenKey, RequestGuid);
            string Token = DigestHelper.MD5Converter(key);
            if (Token != AccessToken)
            {
                ResponseResultInfo error = new ResponseResultInfo();
                error.Description = "非法的Token!";
                actionContext.Response =
                actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, error);
            }
        
            if (SERedisHelper.KeyExists(RequestGuid, 2))
            {
                ResponseResultInfo error = new ResponseResultInfo();
                error.Description = "RequestGuid存在,拒绝访问!";
                actionContext.Response =
                actionContext.Request.CreateResponse(HttpStatusCode.Forbidden, error);
                return;
            }
            TimeSpan sd = new TimeSpan(10, 0, 0);
            SERedisHelper.Set(RequestGuid, 1, sd, 2);
        }
    }
}